package com.jiandan.plugin.task

import com.jiandan.plugin.PluginExtension
import org.gradle.api.Action
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.file.CopySpec
import org.gradle.api.tasks.TaskAction

class FirmDownloadTask extends DefaultTask {


    private PluginExtension config

    FirmDownloadTask() {
        group = "firm360"
        description = "下载360加固"
        config = PluginExtension.getConfig(project)
    }

    @TaskAction
    def download() {
        config.setIsFirmTask(true)
        File firmUnZipPath = new File(config.firmJarPath)
        def strs = config.firmDownloadUrl.split("/")
        File firmZipFile = new File(config.outPath, strs[strs.length - 1])
        if (isNeedDownload(firmUnZipPath, firmZipFile)) {
            downLoadFile(config.firmDownloadUrl, firmZipFile)
            unZip(firmZipFile, firmUnZipPath)
        }
    }

    private def unZip(File firmZipFile, File firmUnZipPath) {
        println("开始解压文件")
        project.copy(new Action<CopySpec>() {
            @Override
            void execute(CopySpec copySpec) {
                copySpec.from(project.zipTree(firmZipFile))
                        .into(firmUnZipPath)
                println("解压文件结束")
            }
        })
    }

    private def downLoadFile(String downloadUrl, File saveFile) {
        println("下载文件地址:$downloadUrl")
        File tempFile = new File(saveFile.parent, "${saveFile.name}.temp")
        println("下载文件路径:${tempFile.absolutePath}")
        if (!saveFile.parentFile.exists()) {
            println("创建文件夹:${saveFile.parentFile.absolutePath}")
            saveFile.parentFile.mkdirs()
        }
        def connection = new URL(downloadUrl).openStream()
        def stream2 = new URL(downloadUrl).openConnection()
        def total = stream2.getContentLength()
        def len
        def hasRead = 0
        byte[] arr = new byte[1024 * 5]
        def out = new FileOutputStream(tempFile)
        def lastResult = 0
        while ((len = connection.read(arr)) != -1) {
            out.write(arr, 0, len)
            hasRead += len
            double progress = hasRead * 100.0 / total
            def progressInt = progress.toInteger()
            if (lastResult != progressInt) {
                lastResult = progressInt
                println("下载进度：" + progressInt + "%")
            }
        }
        connection.close()
        out.close()
        if (hasRead != total) {
            throw new GradleException("360加固压缩包下载失败 长度不对")
        }
        tempFile.renameTo(saveFile)
        println("下载完成")
    }

    private Boolean isNeedDownload(File firmUnZipPath, File firmZipFile) {
        if (!config.firmEnable){
            println("360加固 已经关闭 无需下载")
            return false
        }
        def firmJar = new File(firmUnZipPath, "jiagu/jiagu.jar")
        if (!firmJar.exists()) {
            if (!firmZipFile.exists()) {
                return true
            } else {
                println("检测到本地已存在下载的压缩包")
                unZip(firmZipFile, firmUnZipPath)
                return false
            }
        }
        println("检测到本地已存在360加固解压缩文件")
        return false
    }

    public String getConfig() {
        return this.config
    }
}
